<!-- 组织详情调整编制组件 -->
<template>
  <a-drawer
    :width="800"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> 人员编制 </template>
    <div>
      <div style="display: flex; justify-content: space-between">
        <h1>{{ data.name }}</h1>
        <a-button type="primary" @click="modalClick">调整编制</a-button>
      </div>
      <a-space style="font-size: 16px" size="large">
        <div>
          当前编制:
          <span style="color: #165dff">{{ staffingChangeData.currNum }}</span>
        </div>
        <div>
          超编/缺编:
          <span
            :style="{
              color: staffingChangeData.overNum > 0 ? '#165dff' : 'red'
            }"
          >
            {{ staffingChangeData.overNum }}
          </span>
        </div>
      </a-space>
      <a-descriptions
        :data="staffingChangeData.countPeople"
        title="组织人员概况"
        layout="inline-horizontal"
      />

      <div>
        <a-descriptions title="设置职位编制" layout="inline-horizontal" />
        <div>
          <a-collapse
            :default-active-key="defaultActiveKey"
            :bordered="false"
            v-for="(item, index) in staffingChangeData.tableData"
            :key="item.id"
          >
            <a-collapse-item :key="item.id">
              <template #header>
                <a-space size="large">
                  <span>{{ item.name }} </span>
                  <span>编制： {{ item.num }} </span>
                </a-space>
              </template>
              <template #extra>
                <a-button type="text" @click.stop="changeSub(index)"
                  >调整编制</a-button
                >
              </template>
              <a-table
                :data="item.positions"
                :pagination="false"
                :bordered="false"
                stripe
              >
                <template #columns>
                  <a-table-column data-index="name" title="职位名称">
                    <template #cell="{ record }">
                      <a-input disabled v-model="record.name"></a-input>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="bianzhi" title="编制人数">
                    <template #cell="{ record }">
                      <a-input-number
                        :disabled="currIndex !== index"
                        v-model="record.num"
                        @change="(val, _) => changeSubNum(val, _, record)"
                        hide-button
                      ></a-input-number>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="onJob" title="在职人数">
                    <template #cell="{ record }">
                      <a-input disabled v-model="record.onboarding"></a-input>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </a-collapse-item>
          </a-collapse>
        </div>
      </div>
    </div>
    <Modal
      v-model:visible="subModalVisible"
      :data="data"
      @changeCount="changeCount"
    >
    </Modal>
  </a-drawer>
</template>

<script lang="ts" setup>
import {
  GetOrganizationDetailNumber,
  GetOrganizationDetailHeadCount
} from '@/apis/management/organization/organizationManagement';
import Modal from './Modal.vue';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);
const tableData = reactive([
  {
    id: 1,
    name: '销售部',
    totalBianzhi: 100,
    data: [
      {
        id: 1,
        name: '11111',
        bianzhi: 23000,
        onJob: '32 Park Road, London'
      },
      {
        id: 2,
        name: '22222',
        bianzhi: 23,
        onJob: '32 Park Road, London'
      }
    ]
  },
  {
    id: 2,
    totalBianzhi: 200,
    name: 'IT部',
    data: [
      {
        id: 3,
        name: '33333',
        bianzhi: 23000,
        onJob: '32 Park Road, London'
      },
      {
        id: 4,
        name: '44444',
        bianzhi: 23,
        onJob: '32 Park Road, London'
      }
    ]
  }
]);

const emit = defineEmits(['update:visible', 'staffingChangeEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

const route = useRoute();
// 档案id
const id = +(route.query.id as string);

const staffingChangeData = reactive<any>({
  countPeople: [], // 储存统计人数数据
  tableData: [], // 表格数据，
  currNum: 0, // 当前编制
  overNum: 0 // 超编缺编
});
let defaultActiveKey: number[] = [];
// 获取数据
const getData = async () => {
  try {
    // 获取组织统计人数数据
    const res: any = await Promise.all([
      GetOrganizationDetailNumber({
        id
      }),
      // 调整编制表格数据
      GetOrganizationDetailHeadCount({
        id
      })
    ]);
    // 将返回的数据重新组成新的数组
    staffingChangeData.countPeople = res[0].map((item: any) =>
      Object.assign(
        {},
        {
          label: item.name,
          value: item.value
        }
      )
    );

    staffingChangeData.tableData = res[1];

    // 计算当前编制人数
    let tempOverNum = 0; // 计算临时的在职人数
    res[1].forEach((item1: any) => {
      defaultActiveKey.push(item1.id);
      staffingChangeData.currNum += +item1.num;
      item1.positions?.forEach((item2: any) => {
        tempOverNum += +item2.onboarding;
      });
    });

    staffingChangeData.overNum = tempOverNum - staffingChangeData.currNum;
  } catch (error: unknown) {
    console.log(error);
  }
};

watch(
  () => modalVisible.value,
  (newVal: boolean) => {
    if (newVal) {
      getData();
    }
  }
);

let subModalVisible = ref(false); // 调整编制子弹出框

// 点击调整编制按钮
const modalClick = () => {
  subModalVisible.value = true;
};

// 调整编制弹出框自定义事件
const changeCount = async (formData: any) => {
  try {
    //
  } catch (error: unknown) {
    console.log(error);
  }
};

let currIndex = ref(-1); // 用来判断表格信息是否是disabled

// 改变表格是否为disabled
const changeSub = (index: number) => {
  if (currIndex.value > -1) currIndex.value = -1;
  else currIndex.value = index;
};

let changeNumArr: {
  id: number;
  num: number;
}[] = []; // 储存修改过的编制人数
const changeSubNum = async (val: number, _: Event, record: any) => {
  try {
    changeNumArr.push({
      id: record.id,
      num: record.num
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 保存
const handleOk = () => {
  modalVisible.value = false;
  emit('staffingChangeEmit', changeNumArr);
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
};
</script>

<style scoped lang="less">
:deep(.arco-descriptions-title::before) {
  position: relative;
  display: inline-block;
  content: '';
  width: 4px;
  height: 20px;
  background-color: #165dff;
  margin-right: 5px;
  top: 4px;
  margin-top: 10px;
}
</style>
